package org.snake.nebulae.core.service;

import lombok.extern.slf4j.Slf4j;
import org.snake.nebulae.core.model.MqttResponse;
import org.snake.nebulae.core.model.SubscriptionInfo;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class MetaInfoService {

    private ConcurrentHashMap<String, MqttResponse<SubscriptionInfo>> infos = new ConcurrentHashMap<>();

    private String appId = "admin";

    private String appSecret = "public";

    public Mono<? extends MqttResponse> recordSubscriptions() {
        MqttResponse<SubscriptionInfo> subInfo = new MqttResponse<>();

        return WebClient.builder()
                .defaultHeaders(httpHeaders -> httpHeaders.setBasicAuth(appId, appSecret))
                .build()
                .get()
                .uri(uriBuilder -> {
                    uriBuilder = uriBuilder
                            .scheme("http")
                            .host("localhost")
                            .port("8081")
                            .path("/api/v4/subscriptions/");

                    return uriBuilder.build();
                })
                .retrieve()
                .bodyToMono(new ParameterizedTypeReference<MqttResponse<SubscriptionInfo>>() {
                })
                .map(v -> {
                    System.out.println(v.getClass());
                    return v;
                })
                .doOnError(throwable -> {
                    log.error("失败 请求mqtt信息时 {}", throwable.getMessage());
                })
                .doOnSuccess(items -> {
                    infos.put("topics", items);
                });
    }
}
